package com.boarsoft.boar.deploy.plan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.boar.deploy.bean.BuildInstParam;
import com.boarsoft.boar.deploy.bean.BuildItemParam;
import com.boarsoft.boar.deploy.entity.BuildPlanDetail;
import com.boarsoft.flow.core.bean.ForkHandler;

/**
 * 打包或部署fork并行
 * 
 * @author Mac_J
 *
 */
public class Build1ItemFH implements ForkHandler {
	private static Logger log = LoggerFactory.getLogger(Build1ItemFH.class);

	/** 最多线程数 */
	protected int maxThreads = 5;

	/**
	 * @param key
	 *            ${code}-${version}
	 * @param data
	 *            { env: ${env}, item: BuildPlanItem }
	 * @param throwable
	 *            未使用
	 * @return { k: 目标服务器地址, v: BuildPlanItem }
	 */
	@Override
	public Map<String, Object> fork(String key, Object data, Throwable throwable) {
		BuildItemParam p = (BuildItemParam) data;
		Map<String, Object> rm = new HashMap<>();
		List<BuildPlanDetail> sLt = p.getDetails();
		int i = 0, j = 0, //
				tt = sLt.size(), // 总实例数
				ts = Math.min(tt, maxThreads); // 最大线程数
		List<BuildInstParam> lt = null;
		for (BuildPlanDetail s : sLt) {
			if (i++ % ts == 0) {
				lt = new ArrayList<BuildInstParam>();
				rm.put(String.valueOf(j++), lt);
			}
			lt.add(this.convert(p, s));
		}
		log.info("Fork result = {}", rm);
		return rm;
	}

	protected BuildInstParam convert(BuildItemParam p, BuildPlanDetail d) {
		BuildInstParam r = new BuildInstParam();
		r.setAddr(d.getAddr());
		r.setCode(p.getCode());
		r.setEnv(p.getEnv());
		r.setIp(d.getIp());
		r.setPort(d.getTargetPort());
		r.setTargetPath(d.getTargetPath());
		r.setTaskId(p.getTaskId());
		r.setVersion(p.getVersion());
		return r;
	}

	public int getMaxThreads() {
		return maxThreads;
	}

	public void setMaxThreads(int maxThreads) {
		this.maxThreads = maxThreads;
	}
}